package handler

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"godco/internal/logic"
	"godco/internal/svc"
	"godco/internal/types"
	"godco/internal/utils"
	"net/http"
)

func AuthRequestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.AuthRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewAuthRequestLogic(r.Context(), svcCtx)
		resp, err := l.AuthRequest(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

func TargetInstalledHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.TargetInstallationRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		l := logic.NewAuthRequestLogic(r.Context(), svcCtx)
		resp, err := l.InstallationInfo(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			_, err := utils.GetInstallationAppInfo(resp.InstallId, svcCtx)
			if err != nil {
				httpx.ErrorCtx(r.Context(), w, err)
				return
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

func TargetIsInstalledHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.TargetInstallationRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		l := logic.NewAuthRequestLogic(r.Context(), svcCtx)
		resp, errs := l.InstallationInfo(&req)
		appInfo, err := utils.GetMarketAppInfo(svcCtx)
		isInstalled := false
		installationId := ""
		signUrl := ""
		appInstallationUrl := ""
		if err != nil {

		} else {
			appInstallationUrl = appInfo.HtmlUrl
			IsGetInfo := svcCtx.Config.ApplicationConf.GetInstallInfo
			if errs == nil {
				if IsGetInfo {
					_, err := utils.GetInstallationAppInfo(resp.InstallId, svcCtx)
					if err == nil {
						isInstalled = true
						installationId = resp.InstallId
						signUrl = svcCtx.Config.ApplicationConf.Host + svcCtx.Config.ApplicationConf.Sign + "?aid=" + resp.InstallId
					}
				} else {
					isInstalled = true
					installationId = resp.InstallId
					signUrl = svcCtx.Config.ApplicationConf.Host + svcCtx.Config.ApplicationConf.Sign + "?aid=" + resp.InstallId
				}
			}

		}

		data := &types.TargetIsInstallationResponse{
			Data: types.InstalledResponse{
				IsInstalled:    isInstalled,
				InstallUrl:     appInstallationUrl,
				InstallationId: installationId,
				SignUrl:        signUrl,
			},
			Code: 200,
			Msg:  "success",
		}
		httpx.OkJsonCtx(r.Context(), w, data)
	}
}
